package com.xcc.httpUtils.builder;

import com.xcc.httpUtils.HttpUtils;
import com.xcc.httpUtils.ssl.TrustAllCerts;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Carman
 * <p>
 * Date: 2018/11/26 - 15:03
 * <p>
 * 描述:
 * http 请求build
 */
public class HttpClientBuild {

    private OkHttpClient.Builder mBuilder;
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    public HttpClientBuild(OkHttpClient.Builder builder) {
        if (builder == null) throw new NullPointerException("OkHttpClient.Builder is null");
        mBuilder = builder;
    }

    /**
     * 添加 cookie
     *
     * @return
     */
    public HttpClientBuild cookie() {
        mBuilder.cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                List<Cookie> cookiesList = cookieStore.get(url.host());
//                                    System.out.println("保存: " + cookieStore.keySet());
                if (cookiesList != null) {
                    cookieStore.remove(url.host());
                }
                //再重新添加
                if (cookiesList != null && cookiesList.size() > 0) {
                }
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookiesList = cookieStore.get(url.host());
//                                    System.out.println("加载: " + cookieStore.keySet());
                if (cookiesList != null && cookiesList.size() > 0) {
                }
                return cookiesList != null ? cookiesList : new ArrayList<Cookie>();
            }
        }).build();
        return this;
    }

    /**
     * 添加 ssl 验证
     *
     * @return
     */
    public HttpClientBuild ssl() throws KeyManagementException, NoSuchAlgorithmException {
        final TrustManager[] trustAllCerts = new TrustManager[]{new TrustAllCerts()};
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        mBuilder.sslSocketFactory(sslSocketFactory);
        mBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return this;
    }

    public void init() {
        HttpUtils.initClient(mBuilder.build());
    }
}
